<?php

/**
 * 六象元一 赠品函数库
 * ============================================================================
 * $Author: 王海龙 $
 * $Id: lib_gift.php 17217 2014-11-04 00:00:00Z 王海龙 $
*/

if (!defined('IN_ECS'))
{
    die('Hacking attempt');
}

/**
 * $total_fee  购买商品金额
 * $condition  必要条件
 * $type  赠品类型
 * $id  赠品ID
 * $area_id  服务地区ID
 */
function get_gift_goods_list($total_fee = false, $condition = '', $type = '', $id = '', $area_id = ''){
    $sw = '1';
    // 存在赠品ID时
    if($id) $sw .= " AND gift.id = '$id'";
    // 存在必要条件时
    if($condition) $sw .= " AND gift.condition = '$condition'";
    // 存在金额限制时
    if($total_fee || $total_fee == '0'){
        $total_fee = floatval($total_fee);
        $sw .= " AND (gift.lower_limit <= $total_fee OR gift.lower_limit = 0) AND (gift.upper_limit > $total_fee OR gift.upper_limit = 0)";
    }
    // 存在赠品类型时
    if($type) $sw .= " AND gift.type = '$type'";
    
    $sql = "SELECT * FROM " . $GLOBALS['ecs']->table('gift') . " gift WHERE $sw";
    $gift_list = $GLOBALS['db']->getAll($sql);
    if($gift_list){
        foreach ($gift_list as $key => $value) {
            $sql = "SELECT ga.*, g.*, gg.goods_name, gg.gift_id, gg.goods_number, gg.goods_total, gg.goods_id, gg.goods_attr_id " .
                " FROM " . $GLOBALS['ecs']->table('gift_goods') . " gg LEFT JOIN ". $GLOBALS['ecs']->table('goods') . " g ON g.goods_id = gg.goods_id LEFT JOIN " . $GLOBALS['ecs']->table('goods_attr') . " ga ON ga.goods_attr_id = gg.goods_attr_id WHERE gg.gift_id = $value[id]";
            $goods_list = $GLOBALS['db']->getAll($sql);
            if($goods_list){
                foreach ($goods_list as $k => $v) {
                    $sql = "SELECT sum(goods_number) FROM " . $GLOBALS['ecs']->table('goods_stock') . " gs WHERE gs.goods_sku = $v[goods_sku]" . ($area_id ? " AND gs.area_id = '$area_id'" : '');
                    $goods_stock = $GLOBALS['db']->getOne($sql);
                    $number = intval($goods_stock/$v['goods_number']);
                    $goods_list[$k]['goods_stock'] = $goods_stock;
                    if($number < $gift_list[$key]['number']){
                        $gift_list[$key]['number'] = $number;
                    }

                }
                $gift_list[$key]['goods_list'] = $goods_list;
            }else{
                $sql = "DELETE FROM " . $GLOBALS['ecs']->table('gift') . " WHERE gift_id = $value[id]";
                $GLOBALS['db']->query($sql);
                unset($gift_list[$key]);
            }
        }
    }
    if($id) return $gift_list[0];
    return $gift_list;
}


?>
